package com.zyk.leetcode;

/**
 * @author zhangsan
 * @date 2021/5/10 16:58
 */
public class C1254 {

    // 封闭岛屿的数量, 0代表陆地, 上下左右联通的陆地叫做一块岛屿. 求多少岛屿完全被海包围
    public static int closedIsland(int[][] grid) {
        int R = grid.length, C = grid[0].length;
        int ans = 0;
        for (int r = 0; r < R; r++)
            for (int c = 0; c < C; c++)
                if (grid[r][c] == 0 && !dfs(grid, r, c, R, C))
                    ans++;
        return ans;
    }

    private static boolean dfs(int[][] grid, int r, int c, int R, int C) {
        if (r == 0 || r == R - 1 || c == 0 || c == C - 1 && grid[r][c] == 0) return true;   // 如果到达边界同时这是个陆地, 就不算他被包围
        grid[r][c] = 2;
        boolean noSurrounded = false;   // 默认他被包围了
        if (grid[r + 1][c] == 0)
            noSurrounded = dfs(grid, r + 1, c, R, C);
        if (grid[r - 1][c] == 0)
            noSurrounded |= dfs(grid, r - 1, c, R, C);
        if (grid[r][c + 1] == 0)
            noSurrounded |= dfs(grid, r, c + 1, R, C);
        if (grid[r][c - 1] == 0)
            noSurrounded |= dfs(grid, r, c - 1, R, C);
        return noSurrounded;
    }

    // for test
    public static void main(String[] args) {
        int[][] grid = {
                {0, 0, 1, 1, 0, 1, 0, 0, 1, 0},
                {1, 1, 0, 1, 1, 0, 1, 1, 1, 0},
                {1, 0, 1, 1, 1, 0, 0, 1, 1, 0},
                {0, 1, 1, 0, 0, 0, 0, 1, 0, 1},
                {0, 0, 0, 0, 0, 0, 1, 1, 1, 0},
                {0, 1, 0, 1, 0, 1, 0, 1, 1, 1},
                {1, 0, 1, 0, 1, 1, 0, 0, 0, 1},
                {1, 1, 1, 1, 1, 1, 0, 0, 0, 0},
                {1, 1, 1, 0, 0, 1, 0, 1, 0, 1},
                {1, 1, 1, 0, 1, 1, 0, 1, 1, 0}};
        System.out.println(closedIsland(grid));
    }

}
